package stud.mpgame.physics;

/**
 * ...
 * @author pavel[f.pavel91@gmail.com]
 */
class Vector2D {

	public var x:Float;
	public var y:Float;
	
	public function new(x:Float, y:Float) {
		this.x = x;
		this.y = y;
	}

	public inline function set(x:Float, y:Float) {
		this.x = x;
		this.y = y;
	}

	public inline function dot(v:Vector2D) {
		return x * v.x + y * v.y;
	}

	public inline function cross(v:Vector2D) {
		return x * v.y - y * v.x;
	}

	public inline function addDot(dx:Float, dy:Float) {
		this.x += dx;
		this.y += dy;
	}
	
	public inline function add(v:Vector2D) {
		this.x += v.x;
		this.y += v.y;
	}
	
	public inline function addNew(v:Vector2D) {
		return new Vector2D(x + v.x, y + v.y);
	}

	public inline function sub(v:Vector2D):Vector2D {
		return new Vector2D(x - v.x, y - v.y);
	}


	public inline function mul(s:Float):Vector2D {
		return new Vector2D(x * s, y * s);
	}

	public inline function length():Float {
		return Math.sqrt(x * x + y * y);
	}

	public function toString():String {
		return "("+(Math.round(x*100)/100)+","+(Math.round(y*100)/100)+")";
	}

	public static inline function normal(x:Float, y:Float):Vector2D {
		var d = Math.sqrt(x * x + y * y);
		var k = if( d < 1e-99 ) 0 else 1 / d;
		return new Vector2D( -y * k , x * k );
	}
	
	public function projection(v:Vector2D):Vector2D {
		var scalar = dot(v);
		var squareLength = v.x * v.x + v.y * v.y;
		var projX:Float = ( scalar / squareLength ) * v.x;
		var projY:Float = ( scalar / squareLength ) * v.y;
		return new Vector2D(projX, projY);
	}
	
}